<?php

class Db_Tables_Extensions
{
	private $appId;
	private $appSecret;

	function __construct() {
		$this->db = Zend_Registry::get("db");
		$this->appId = "wx0a0a571c5f63f74e";
		$this->appSecret = "5029587efbe01533ea24f573bcdc2411";
	}

    function RandomSerialNumber($length)
    {
        $code = 'AaBbCcDeEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz';

        $rand = $code[rand(0,50)]
            .strtoupper(dechex(date('m')))
            .date('d').substr(time(),-5)
            .substr(microtime(),2,5)
            .sprintf('%02d',rand(0,99));

        for(
            $a = md5( $rand, true ),
            $s = '0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVv',
            $d = '',
            $f = 0;
            $f < $length;
            $g = ord( $a[ $f ] ),
            @$d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
            $f++
        );
        return $d;
    }

    function GetContractsCode($exchange_code, $dig)
    {
        if($dig++ < 10)
        {

            $mod_couponss = new Db_Tables_Coupons();

            $row = $mod_couponss->fetchRow("coupon_code='".$exchange_code."'");

            if(isset($row->coupon_code))
            {
                $i = 8;
                if($dig > $i)
                {
                    $i = $dig;
                }
                $exchange_code = $this->RandomSerialNumber($i);
                $this->GetContractsCode($exchange_code, $dig);
            }
            else
            {
                return $exchange_code;
            }
        }
        else
        {
            return $exchange_code;
        }
    }

    function FormatArray($array)
	{
		if(is_array($array))
		{
			echo "<pre>";
			print_r($array);
			echo "<pre>";
		}else{
			echo "Not an array.";
		}
	}
	
	function TurnMsgToObj($post_str)
	{
		if(!empty($post_str))
		{
			$result = simplexml_load_string($post_str, 'SimpleXMLElement', LIBXML_NOCDATA);
		}else{
			$result = NULL;
		}
		
		return $result;
	}
	
	function WelcomeMsg($postObj)
	{
		$toUser = $postObj->FromUserName;
		$fromUser = $postObj->ToUserName;
		$createTime = time();
		
		$mod_params = new Db_Tables_Params();
		$wechat_welcome_info = $mod_params->WechatWelcomeInfo();
		
		//make relation for recommendation start
		if($postObj->EventKey)
		{
			$mod_subscribe = new Db_Tables_LogsSubscribe();
			$mod_subscribe->key = $postObj->EventKey;
			$mod_subscribe->open_id = $toUser;
			$mod_subscribe->AddRecord();
		}
		//make relation for recommendation end
		
		$items = '';
		
		$num = 0;
		
		for($n=1;$n<6;$n++)
		{
			if($wechat_welcome_info['wechat-welcome-'.$n])
			{
				$items .= "<item>
						<Title><![CDATA[".$wechat_welcome_info['wechat-welcome-'.$n.'-title']."]]></Title> 
						<Description><![CDATA[".$wechat_welcome_info['wechat-welcome-'.$n.'-desc']."]]></Description>
						<PicUrl><![CDATA[".$wechat_welcome_info['SYS_DOMAIN'].$wechat_welcome_info['wechat-welcome-'.$n.'-picture']."?".date("s")."]]></PicUrl>
						<Url><![CDATA[".$wechat_welcome_info['wechat-welcome-'.$n.'-url']."]]></Url>
						</item>";
				
				$num += 1;
			}
		}
		
		$result = "<xml>
						<ToUserName><![CDATA[".$toUser."]]></ToUserName>
						<FromUserName><![CDATA[".$fromUser."]]></FromUserName>
						<CreateTime>".$createTime."</CreateTime>
						<MsgType><![CDATA[news]]></MsgType>
						<ArticleCount>".$num."</ArticleCount>
						<Articles>".$items."</Articles></xml>";
		
		return $result;
	}
	
	function QiangQuan($postObj)
	{
		$toUser = $postObj->FromUserName;
		$fromUser = $postObj->ToUserName;
		$createTime = time();
		
		$contents = "直播啦，品日料玩抽奖劲爆嗨翻天，点击下方抽奖链接秒传送http://m.grouplus.com/I3tULC";
		
		$result = "<xml>
						<ToUserName><![CDATA[".$toUser."]]></ToUserName>
						<FromUserName><![CDATA[".$fromUser."]]></FromUserName>
						<CreateTime>".$createTime."</CreateTime>
						<MsgType><![CDATA[text]]></MsgType>
						<Content><![CDATA[".$contents."]]></Content>
					</xml>";
		
		return $result;
	}
	
	function ShareMe($postObj)
	{
		$toUser = $postObj->FromUserName;
		$fromUser = $postObj->ToUserName;
		$createTime = time();
		
		$contents = "ceshi";
		
		$result = "<xml>
						<ToUserName><![CDATA[".$toUser."]]></ToUserName>
						<FromUserName><![CDATA[".$fromUser."]]></FromUserName>
						<CreateTime>".$createTime."</CreateTime>
						<MsgType><![CDATA[text]]></MsgType>
						<Content><![CDATA[".$contents."]]></Content>
					</xml><xml>
						<ToUserName><![CDATA[".$toUser."]]></ToUserName>
						<FromUserName><![CDATA[".$fromUser."]]></FromUserName>
						<CreateTime>".$createTime."</CreateTime>
						<MsgType><![CDATA[text]]></MsgType>
						<Content><![CDATA[".$contents."]]></Content>
					</xml>";
		
		return $result;
	}
	
	function SendVcode($cellphone)
	{
		//create vcode
		$mod_veri = new Db_Tables_CellphoneVerification();
		$vcode = $mod_veri->AddVcode($cellphone);
		
		//send sms
		$send_result = $this->SendVerifyCode($cellphone, $vcode);
		return $send_result;
	}
	
	function SendVerifyCode($target_num, $verify_code)
	{
		$result = array(
			'result' => 0,
			'reason' => "未知错误"
		);
		
		$mod_ext = new Sys_Extensions();
		
		$url = "https://api.sms.jpush.cn/v1/messages";
		
		$data_array = array(
			"mobile" => trim($target_num),
			"temp_para" => array("code" => $verify_code),
			"temp_id" => 1
		);
		
		$type = 1;
		
		$header = array(
			"Content-Type: application/json",
			"Authorization: Basic ". base64_encode("f11dfcb6c20c29d3bb6fb5ac:396bffc44689a22ca684d520")
		);
		
		$fb = $mod_ext->Broadcast($url, $data_array, $type, 1, $header);
		
		if($fb['error'])
		{
			$result['reason'] = $fb['error']['message'];
		}else{
			$result = array(
				'result' => 1,
				'reason' => "发送成功"
			);
		}
	
		return $result;
	}
	
	function SendWxTemplateMsg($agent_id, $template_key, $data_arr)
	{
		if($agent_id && $template_key && is_array($data_arr))
		{
			$template = array(
				"AGENTNEW" => array(
					"temp_id" => "4Nz0T0wWM3cr-K4OPaRj3sSoldLPkt8sAis7fBiJmiI",
					"url" => "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8dc6d2094ab101eb&redirect_uri=".urlencode("http://wx.jintongyuda.com")."&response_type=code&scope=snsapi_userinfo&state=wom#wechat_redirect"
				),
				"AGENTUPGRADE" => array(
					"temp_id" => "Ta6IxCH3K8U1SVtZyD_YaUNiYVf6vc3ncF7uXyWZOEI",
					"url" => "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8dc6d2094ab101eb&redirect_uri=".urlencode("http://wx.jintongyuda.com")."&response_type=code&scope=snsapi_userinfo&state=wom#wechat_redirect"
				),
				"AGENTLEVELCONFIRM" => array(
					"temp_id" => "w4TKo9m_Wjj7MfTabeonqv1J1ZrWcqwU562kF_qlGCo",
					"url" => "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8dc6d2094ab101eb&redirect_uri=".urlencode("http://wx.jintongyuda.com")."&response_type=code&scope=snsapi_userinfo&state=wom#wechat_redirect"
				),
				"NEWORDER" => array(
					"temp_id" => "nTsCxqQ1EG96Vuhqk7Ma2U0sTKwbJV6rUqz87MCo7js",
					"url" => "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8dc6d2094ab101eb&redirect_uri=".urlencode("http://wx.jintongyuda.com")."&response_type=code&scope=snsapi_userinfo&state=wom#wechat_redirect"
				),
				"WITHDRAWAPPLY" => array(
					"temp_id" => "2w4bITTwMmrMON0ycOxT-_Mn9nLsQhLoNcIA4wXWtYk",
					"url" => "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8dc6d2094ab101eb&redirect_uri=".urlencode("http://wx.jintongyuda.com")."&response_type=code&scope=snsapi_userinfo&state=wom#wechat_redirect"
				),
				"WITHDRAWCOMPLETE" => array(
					"temp_id" => "__Z1ESyi4Ittm4ieIpkmQEupwwtQvo2PF9NM_KJKjkw",
					"url" => "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8dc6d2094ab101eb&redirect_uri=".urlencode("http://wx.jintongyuda.com")."&response_type=code&scope=snsapi_userinfo&state=wom#wechat_redirect"
				),
				"BONUSNOTICE" => array(
					"temp_id" => "MqCm4TeuxlxELr9YbowyOJlHuQeb9Y3aHHZA3Ut1Zo4",
					"url" => "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8dc6d2094ab101eb&redirect_uri=".urlencode("http://wx.jintongyuda.com")."&response_type=code&scope=snsapi_userinfo&state=wom#wechat_redirect"
				)
			);
			
			$mod_agents = new Db_Tables_Agents();
			$agent_info = $mod_agents->GetSpecifiedAgentInfo($agent_id);
			$open_id = $agent_info['wechat_openid'];
			
			if($open_id && isset($template[$template_key]))
			{
				$data = array(
					"touser" => $open_id,
					"template_id" => $template[$template_key]['temp_id'],
					"url" =>$template[$template_key]['url'],
					"topcolor" => "#FF0000",
					"data" => $data_arr
				);
				
				$url = "http://wx.jintongyuda.com/mp/wat";
				$data_array = array();
				$type = 2;

				$mod = new Sys_Extensions();
				$access_token = $mod->Broadcast($url, $data_array, $type);
				
				if($access_token)
				{
					$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
					$this->Broadcast($url, $data, 1);
				}
			}
		}
		
		return TRUE;
	}
	
	function Broadcast($url, $data_array, $type, $to_json=1, $header=null) //type=1 POST type=2 GET
	{
		$result = NULL;
		
		if(1 == $type)
		{
			$type_txt = "POST";
		}else{
			$type_txt = "GET";
		}
		
		$ch = curl_init();
    	curl_setopt($ch, CURLOPT_URL, $url);
    	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type_txt);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		
		if($to_json)
		{
			$data_str = Zend_Json::encode($data_array);
			
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
		}else{
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data_array);
		}
		
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		
		if($header)
		{
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		}
		
		try {
			$tmpInfo = curl_exec($ch);
	//		var_dump($tmpInfo);die;

	//		$mod_log1 = new Db_Tables_Log1();
	//		$mod_log1->AddLog("Broadcast AAA: ".$tmpInfo);

			if (curl_errno($ch)) {
				echo 'Errno'.curl_error($ch);
			}
			curl_close($ch);

			if($this->is_not_json($tmpInfo))
			{
				$result = trim($tmpInfo);
			}else{
				$result = Zend_Json::decode($tmpInfo);
			}
		} catch (Exception $e) {
			$mod_log1 = new Db_Tables_Log1();
			$mod_log1->AddLog("Broadcast Error: ".$url);
		}
		
		return $result;
	}
	
	function is_not_json($str){ 
		return is_null(json_decode($str));
	}
	
	function MakeSign($data_array)
	{
	    //一样的
		$api_key = '837d838fd05ab8f7e12f78bfcd5537fe';
		
		ksort($data_array);
		
		$str_array = array();
		
		foreach($data_array as $key => $val)
		{
			$val = trim($val);
			
			if($val)
			{
				$str_array[] = $key."=".$val;
			}
		}
		
		$params_str = "";
		
		if(!empty($str_array))
		{
			$params_str = implode("&", $str_array);
		}
		
		$params_str .= "&key=".$api_key;
		
		return strtoupper(md5($params_str));
	}
	
	function DayForDisplay($dt) //$dt datetime
	{
		$result = "";
		
		$a = mktime(substr($dt,11,2),substr($dt,14,2),substr($dt,17,2),substr($dt,5,2),substr($dt,8,2),substr($dt,0,4));
		
		$diff = $a - time();
		
		if(3600 * 24 <= $diff) //display day
		{
			$result = floor($diff / (3600 * 24) + 1)."天";
		}elseif(3600 <= $diff) //display hour
		{
			$result = floor($diff / 3600 + 1)."小时";
		}else //display min
		{
			$result = floor($diff / 60 + 1)."分钟";
		}
		
		return $result;
	}
	
	function GetGeo($city, $address)
	{
		$mod_params = new Db_Tables_Params();
		$key = $mod_params->GetVal("AMAP_WEB_KEY");
		
		$uri= "http://restapi.amap.com/v3/geocode/geo?key=".$key."&city=".urlencode(trim($city))."&address=".urlencode(trim($address));
		$data_str = "";
			
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $uri);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);

		if (curl_errno($ch)) {
			echo 'Errno'.curl_error($ch);
		}
		curl_close($ch);

		$result = Zend_Json::decode($tmpInfo);
		
		if(is_array($result) && $result['count'])
		{
			$target_adds = array(
				'result' => 1,
				'city' => trim($city),
				'address' => $address,
				'geo' => $result['geocodes'][0]['location']
			);
		}else{
			$target_adds = array("result" => 0);
		}
		
		return $target_adds;
	}
	
	function searchConfirm($city,$address){
		
		$mod_params = new Db_Tables_Params();
		$key = $mod_params->GetVal("AMAP_WEB_KEY");
		$uri ="http://restapi.amap.com/v3/place/text?&keywords={$address}&city={$city}&output=JSON&offset=20&page=1&key={$key}&extensions=all";
		$data_str = "";
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $uri);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);
		
		if (curl_errno($ch)) {
			echo 'Errno'.curl_error($ch);
		}
		curl_close($ch);
		
		$result = Zend_Json::decode($tmpInfo);
		if(is_array($result) && $result['status']&& !empty($result['pois']))
		{
			$targets = array(
				'result' => 1,
				'addr' => array()
			);
			
			foreach($result['pois'] as $pois)
			{
				$targets['addr'][] = $pois['name'];
				if($pois['pname']==$pois['cityname']){
					$targets['addr'][$pois['name']]['detail']=$pois['cityname'].$pois['adname'].$pois['address'];
				}else{
					$targets['addr'][$pois['name']]['detail']=$pois['pname'].$pois['cityname'].$pois['adname'].$pois['address'];
				}
				
			}
		}else{
			$targets  = array("result" => 0);
		}
		
		return $targets ;
	}
	
	
	function GetGeoDistance($origin, $destination)
	{
		$mod_params = new Db_Tables_Params();
		$key = $mod_params->GetVal("AMAP_WEB_KEY");
		
		$uri = "http://restapi.amap.com/v3/direction/walking?key=".$key."&origin=".$origin."&destination=".$destination;
		$data_str = "";
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $uri);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);

		if (curl_errno($ch)) {
			echo 'Errno'.curl_error($ch);
		}
		curl_close($ch);

		$result = Zend_Json::decode($tmpInfo);
		
		if(is_array($result) && $result['status'])
		{
			$target_adds = array(
				'result' => 1,
				'distance' => $result['route']['paths'][0]['distance'], //米
				'duration' => $result['route']['paths'][0]['duration'] //秒
			);
		}else{
			$target_adds = array("result" => 0);
		}
		
		return $target_adds;
	}
	
	function GetClosestShopId($city_id, $target_geo)
	{
		$result = array();
		
		$mod_params = new Db_Tables_Params();
		$key = $mod_params->GetVal("AMAP_WEB_KEY");
		//$valid_distance = 4000; //最远支持配送4公里
		$valid_distance = 10000; //最远支持配送10公里
		$valid_distance2 = 4000;
		
		$mod_shops = new Db_Tables_Shops();
		$shops_str = $mod_shops->MakeShopsString($city_id);
		
		$uri = "http://restapi.amap.com/v3/distance?key=".$key."&origins=".$shops_str['str']."&destination=".$target_geo."&type=3";
		$data_str = "";
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $uri);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);

		if (curl_errno($ch)) {
			echo 'Errno'.curl_error($ch);
		}
		curl_close($ch);

		$lbs_info = Zend_Json::decode($tmpInfo);
		
		if(is_array($lbs_info) && $lbs_info['status'])
		{
			if(!empty($lbs_info['results']))
			{
				$shortest_id = 0;
				$shortest_distance = 0;
				
				foreach($lbs_info['results'] as $lbi)
				{
					if("-1" != $lbi['distance'])
					{
						if(!$shortest_distance)
						{
							$shortest_distance = $lbi['distance'];
							$shortest_id = $lbi['origin_id'];
						}elseif($shortest_distance > $lbi['distance'])
						{
							$shortest_distance = $lbi['distance'];
							$shortest_id = $lbi['origin_id'];
						}
					}
				}
				
				if($shortest_distance && $shortest_distance <= $valid_distance)
				{
					$validDistance=true;//是否可以下单
					if($shortest_distance > $valid_distance2){
						$validDistance=false;//是否可以下单
					}
					$result = array(
						'distance'=> $shortest_distance,
						'validDistance'=>$validDistance,
						'shop_id' => $shops_str['shop_ids'][$shortest_id],
						'geo' => $target_geo
					);
				}
			}
		}
		
		return $result;
	}
	function GetShopsDistance($city_id, $target_geo)
	{
		$result = array();
		
		$mod_params = new Db_Tables_Params();
		$key = $mod_params->GetVal("AMAP_WEB_KEY");
		
		$mod_shops = new Db_Tables_Shops();
		$shops_str = $mod_shops->MakeShopsString($city_id);
		
		$uri = "http://restapi.amap.com/v3/distance?key=".$key."&origins=".$shops_str['str']."&destination=".$target_geo."&type=0";
		$data_str = "";
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $uri);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);

		if (curl_errno($ch)) {
			echo 'Errno'.curl_error($ch);
		}
		curl_close($ch);

		$lbs_info = Zend_Json::decode($tmpInfo);
		
		if(is_array($lbs_info) && $lbs_info['status'])
		{
			if(!empty($lbs_info['results']))
			{
			    foreach ($lbs_info['results'] as $key=>$destance){
			        $result[$destance['distance']] = $shops_str['shop_ids'][$key+1];
			    }
			    
			}
		}
		ksort($result);
		return $result;
	}
	
	function GetCityIdFromIp()
	{
		$result = 1; //默认宁波
		
		$ip = $this->GetIp();
		
		$mod_params = new Db_Tables_Params();
		$key = $mod_params->GetVal("AMAP_WEB_KEY");
		
		$uri = "http://restapi.amap.com/v3/ip?key=".$key."&ip=".$ip;
		$data_str = "";
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $uri);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);

		if (curl_errno($ch)) {
			echo 'Errno'.curl_error($ch);
		}
		curl_close($ch);

		$lbs_info = Zend_Json::decode($tmpInfo);
		
		if(is_array($lbs_info) && $lbs_info['status'])
		{
			$mod_cities = new Db_Tables_ParamsCity();
			$row = $mod_cities->fetchRow("adcode='".$lbs_info['adcode']."'");
			
			if($row)
			{
				$result = $row->city_id;
			}
		}
		
		return $result;
	}
	
	function GetIp() {
		if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
			$ip = getenv("HTTP_CLIENT_IP");
		} elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
			$ip = getenv("HTTP_X_FORWARDED_FOR");
		} elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
			$ip = getenv("REMOTE_ADDR");
		} elseif (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
			$ip = $_SERVER['REMOTE_ADDR'];
		} else {
			$ip = "unknown";
		}
		
		return ($ip);
	}
	
	function GetAround($geo,$keywords)
	{
		$mod_params = new Db_Tables_Params();
		$key = $mod_params->GetVal("AMAP_WEB_KEY");
		
		if($keywords){
			$uri= "http://restapi.amap.com/v3/place/around?key=".$key."&location=".$geo."&keywords={$keywords}&types=12&radius=600&offset=25&extensions=all";
		}else{
			$uri= "http://restapi.amap.com/v3/place/around?key=".$key."&location=".$geo."&keywords=&types=12&radius=600&offset=25&extensions=all";
		}
		
			
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $uri);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);

		if (curl_errno($ch)) {
			echo 'Errno'.curl_error($ch);
		}
		curl_close($ch);
		
		$result = Zend_Json::decode($tmpInfo);
		
		if(is_array($result) && $result['status'] && !empty($result['pois']))
		{
			$targets = array(
				'result' => 1,
				'addr' => array()
			);
			
			foreach($result['pois'] as $pois)
			{
				$targets['addr'][] = $pois['name'];
				if($pois['pname']==$pois['cityname']){
					$targets['addr'][$pois['name']]['detail']=$pois['pname'].$pois['adname'].$pois['address'];
				}else{
					$targets['addr'][$pois['name']]['detail']=$pois['pname'].$pois['cityname'].$pois['adname'].$pois['address'];
				}
				
			}
		}else{
			$targets = array("result" => 0);
		}
		return $targets;
	}
	
	function WechatUrlDecolation($url)
	{
		$mod_params = new Db_Tables_Params();
		
		return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$mod_params->GetVal("WECHAT_AppID")."&redirect_uri=".urlencode($url)."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
	}
	
	function GetFutureDays()
	{
		$result = array();
		
		$d_key = date("Y-m-d");
		$w = date("w");
		$w_text = $this->GetDayText($w);
		
		$result[$d_key] = "今天 ".$w_text;
		
		$d_key = date("Y-m-d", mktime(date("H"),date("i"),date("s"),date("m"),date("d")+1,date("Y")));
		$d_display = date("m月d日", mktime(date("H"),date("i"),date("s"),date("m"),date("d")+1,date("Y")));
		$w = date("w", mktime(date("H"),date("i"),date("s"),date("m"),date("d")+1,date("Y")));
		$w_text = $this->GetDayText($w);
		
		$result[$d_key] = $d_display." ".$w_text;
		
		$d_key = date("Y-m-d", mktime(date("H"),date("i"),date("s"),date("m"),date("d")+2,date("Y")));
		$d_display = date("m月d日", mktime(date("H"),date("i"),date("s"),date("m"),date("d")+2,date("Y")));
		$w = date("w", mktime(date("H"),date("i"),date("s"),date("m"),date("d")+2,date("Y")));
		$w_text = $this->GetDayText($w);
		
		$result[$d_key] = $d_display." ".$w_text;
		
		$d_key = date("Y-m-d", mktime(date("H"),date("i"),date("s"),date("m"),date("d")+3,date("Y")));
		$d_display = date("m月d日", mktime(date("H"),date("i"),date("s"),date("m"),date("d")+3,date("Y")));
		$w = date("w", mktime(date("H"),date("i"),date("s"),date("m"),date("d")+3,date("Y")));
		$w_text = $this->GetDayText($w);
		
		$result[$d_key] = $d_display." ".$w_text;
		
		return $result;
	}
	
	function GetDayText($w)
	{
		$day = "";
		
		if(is_numeric($w))
		{
			switch($w)
			{
				case 1:
					$day = "周一";
					break;
				case 2:
					$day = "周二";
					break;
				case 3:
					$day = "周三";
					break;
				case 4:
					$day = "周四";
					break;
				case 5:
					$day = "周五";
					break;
				case 6:
					$day = "周六";
					break;
				default :
					$day = "周日";
					break;
			}
		}
		
		return $day;
	}
	
	function ResizeJpg($imgsrc,$imgwidth,$imgheight)
	{
		//$imgsrc jpg格式图像路径 $imgdst jpg格式图像保存文件名 $imgwidth要改变的宽度 $imgheight要改变的高度
		//取得图片的宽度,高度值
		$arr = getimagesize($imgsrc);
		$imgWidth = $imgwidth;
		$imgHeight = $imgheight;
		// Create image and define colors
		$imgsrc = imagecreatefromjpeg($imgsrc);
		$image = imagecreatetruecolor($imgWidth, $imgHeight); //创建一个彩色的底图
		imagecopyresampled($image, $imgsrc, 0, 0, 0, 0,$imgWidth,$imgHeight,$arr[0], $arr[1]);
		
		return $image;
	} 
	
	function GenerateMyShareJpg()
	{
		$result = "";
		
		$mod_params = new Db_Tables_Params();
		$mod_members = new Db_Tables_Members();
		
		$qr_code_with_member_id = "";
		
		$access_token = $mod_params->GetVal("ACCESS_TOKEN");
		
		$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
		$data_array = array(
			"expire_seconds" => 2592000,
			"action_name" => "QR_SCENE",
			"action_info" => array(
				"scene" => array(
					"scene_id" => $_SESSION['identity']['member_id']
				)
			)
		);
		$type = 1;
		
		$ticket = $this->Broadcast($url, $data_array, $type);
		
		if($ticket["ticket"])
		{
			$qr_code_with_member_id = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket["ticket"]);
		}else{
			$mod_params = new Db_Tables_Params();
			$mod_params->RefreshAccessToken();
			
			$access_token = $mod_params->GetVal("ACCESS_TOKEN");

			$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
			$data_array = array(
				"expire_seconds" => 2592000,
				"action_name" => "QR_SCENE",
				"action_info" => array(
					"scene" => array(
						"scene_id" => $_SESSION['identity']['member_id']
					)
				)
			);
			$type = 1;

			$ticket = $this->Broadcast($url, $data_array, $type);

			if($ticket["ticket"])
			{
				$qr_code_with_member_id = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket["ticket"]);
			}
		}
		
		if($qr_code_with_member_id)
		{	
			$imgwidth = $imgheight = 250;
			
			$qr = $this->ResizeJpg($qr_code_with_member_id, $imgwidth, $imgheight);
			
			$bg_path = './images/ads/weshare_bg.jpg';
			$bg = imagecreatefromstring(file_get_contents($bg_path));
			
			imagecopymerge($bg, $qr, 260,275, 0, 0, $imgwidth, $imgheight, 100);
			
			imagejpeg($bg, "./images/ads/my-share/".$_SESSION['identity']['member_id'].".jpg", 100);
			
			$result = $_SESSION['identity']['member_id'].".jpg";
			
			imagedestroy($bg);
			imagedestroy($qr);
		}
		
		return $result;
	}
	
	function GeneratePcEventsJpg($event_id)
	{
		$result = "";
		
		$mod_params = new Db_Tables_Params();
		$mod_members = new Db_Tables_Members();
		
		$qr_code_with_member_id = "";
		$head_image = "";
		$nick_name = "";
		
		if($_SESSION['identity']['member_id'])
		{
			$mod_members->member_id = $_SESSION['identity']['member_id'];
			$member_info = $mod_members->GetMemberInfo();
			$head_image = $member_info['headimgurl'];
			$nick_name = $member_info['member_name'];
		}
		
		$access_token = $mod_params->GetVal("ACCESS_TOKEN");
		
		$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
		$data_array = array(
			"action_name" => "QR_LIMIT_STR_SCENE",
			"action_info" => array(
				"scene" => array(
					"scene_str" => "PC_EVENT_".$event_id
				)
			)
		);
		$type = 1;
		
		$ticket = $this->Broadcast($url, $data_array, $type);
		
		if($ticket["ticket"])
		{
			$qr_code_with_member_id = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket["ticket"]);
		}
		
		echo "<img src='".$qr_code_with_member_id."' /><br />";
		
		return $result;
	}
	
	function LabelDecolation($orders_info_for_label)
	{
		$result = array(
			'order_qty' => 0,
			'contents' => array()
		);
		
		$n = 0;
		
		if(is_array($orders_info_for_label))
		{
			foreach($orders_info_for_label as $od)
			{
				$n += 1;
				
				$contents_1 = "<style> table,td,th {border: 0px solid black;border-style: solid;border-collapse: collapse;font-family:'黑体';font-size:12px;}</style><table><tr><td width='220'>订单编号：".$order_info_for_label['order_basic_info']['shop_pre'].$order_info_for_label['order_basic_info']['order_id']."</td></tr><tr><td>下单时间：</td><td width='40'>".$order_info_for_label['order_basic_info']['ctime']."</td></tr></table>";
//			
//				//preparation for contents 2
//    			$header_string = "<style> table,td,th {border: 0px solid black;border-style: solid;border-collapse: collapse;font-family:'黑体';font-size:12px;}</style><table><tr><td colspan='4' align='center' width='290'>-----------------------------------------------</td></tr><tr><td width='40' align='center'>&nbsp;</td><td width='150'>菜品名称</td><td width='50' align='right'>数量</td><td width='50' align='right'>小计</td></tr>";
//    			
//    			$products_string = "";
//    			
//    			if(!empty($order_info_for_label['order_product_info']))
//    			{
//    				$t = 1;
//					
//					foreach($order_info_for_label['order_product_info'] as $products)
//    				{
//    					$products_string .= "<tr><td width='40' align='center'>".$t."</td><td width='150'>".$products['product_name']."</td><td width='50' align='right'>".$products['qty']."</td><td width='50' align='right'>".number_format($products['qty']*$products['unit_price'],0,".",",")."</td></tr>";
//    				}
//    			}
//				
//    			$payment_string = "<tr><td colspan='4' align='center'>-----------------------------------------------</td></tr><tr><td colspan='2'>合　　计：</td><td colspan='2' align='right'>".$order_info_for_label['order_amount']."</td></tr>";
//    			
//    			$delivery_string = "<tr><td colspan='4' align='center'>-----------------------------------------------</td></tr><tr><td>地址：</td><td colspan='4'>".$order_info_for_label['addr'].$order_info_for_label['addr_details']."</td></tr><tr><td>电话：</td><td colspan='4'>".$order_info_for_label['cellphone']."</td></tr><tr><td>备注：</td><td colspan='4'>".$order_info_for_label['comments']."</td></tr>";
//
//    			$ending_string = "<tr><td colspan='4' align='center'>===============================================</td></tr><tr><td colspan='4' align='center'>用心只为极致体验</td></tr><tr><td colspan='4' align='center'>欢迎关注公众号：全民料理</td></tr><tr><td colspan='4' align='center'>".$order_info_for_label['ctime']."</td></tr></table>";	
			
				$contents_2 = $header_string.$products_string.$payment_string.$delivery_string.$ending_string;
				
				$result['contents'][] = array(
					'contents_1' => $contents_1,
					'contents_2' => $contents_2
				);
			}
		}
		
		$result['order_qty'] = $n;
		
		return $result;
	}
	
	function SingleLabelDecolation($order_info_for_label)
	{
		$contents = "<style> table,td,th {border: 0px solid black;border-style: solid;border-collapse: collapse;font-family:'黑体';}</style><table><tr style='font-size:12px;'><td width='230' colspan='4'>订单编号：".$order_info_for_label['order_basic_info']['shop_pre'].$order_info_for_label['order_basic_info']['order_id']."<br>下单时间：".$order_info_for_label['order_basic_info']['ctime']."</td></tr>";
		
		//preparation for contents 2
    	$contents .= "<tr style='font-size:12px;'><td colspan='4' align='center'>-------------------------------------</td></tr>";
    	
    	$products_string = "";
    	
    	if(!empty($order_info_for_label['order_product_info']))
    	{
    		$t = 1;
				
			foreach($order_info_for_label['order_product_info'] as $products)
    		{
    			$products_string .= "<tr style='font-size:12px;'><td width='30'>".$t."</td><td width='100'>".$products['product_name']."</td><td align='center' width='50'>x".$products['qty']."</td><td align='right' width='50'>".number_format($products['qty']*$products['unit_price'],2,".",",")."</td></tr>";
    		
				$t += 1;
			}
    	}
		
		$line = "<tr style='font-size:12px;'><td colspan='4' align='center'>-------------------------------------</td></tr>";
		
		$contents .= $products_string.$line;
		
		if(!empty($order_info_for_label['order_coupon_info']))
    	{
    		foreach($order_info_for_label['order_coupon_info'] as $coupons)
    		{
    			$contents .= "<tr style='font-size:10px;'><td colspan='2'>产品券：".$coupons['product_name']."</td><td align='center'>x1</td><td align='right'>-".number_format($coupons['product_price'],2,".",",")."</td></tr>";
			}
    	}
		
		$contents .= "<tr style='font-size:10px;'><td width='100' colspan='2'>配送费：</td><td align='right' width='130' colspan='2'>".$order_info_for_label['order_basic_info']['delivery_fee']."</td></tr>";
		
		$contents .= "<tr style='font-size:12px;'><td colspan='4' align='center'>-------------------------------------</td></tr>";
    		
    	$contents .= "<tr style='font-size:14px;'><td width='100' colspan='2'>合　　计：</td><td align='right' width='130' colspan='2'>".$order_info_for_label['order_basic_info']['order_amount']."</td></tr>";
    	
    	$contents .= "<tr style='font-size:12px;'><td colspan='4' align='center'>-------------------------------------</td></tr>";
		
		$contents .= "<tr style='font-size:16px;' height='60'><td colspan='4'>".$order_info_for_label['order_basic_info']['addr'].$order_info_for_label['order_basic_info']['addr_details']."<br>".$order_info_for_label['order_basic_info']['customer_name']."&nbsp;&nbsp;&nbsp;".$order_info_for_label['order_basic_info']['cellphone']."</td></tr>";
		
		$contents .= "<tr style='font-size:11px;'><td colspan='4'>";
		
		if($order_info_for_label['order_basic_info']['invoice'])
		{
			$contents .= "发票：".$order_info_for_label['order_basic_info']['invoice']."<br>";
		}
		
		if($order_info_for_label['order_basic_info']['comments'])
		{
			$contents .= "备注：".$order_info_for_label['order_basic_info']['comments'];
		}
		
		if(2 == $order_info_for_label['order_basic_info']['eta_type'])
		{
			$contents .= "<br>预约：".$order_info_for_label['order_basic_info']['eta']."<br><br><br><br></td></tr>";
		}else{
			$contents .= "<br><br><br><br></td></tr>";
		}
		
		$contents .= "</table>";
		
		$result = array(
			'contents' => $contents
		);
		
		return $result;
	}
	
	function AddScanRecord($postObj)
	{
		$result = false;
		
		$toUser = $postObj->FromUserName;
		$key = $postObj->EventKey;
		
		$mod_wechat_scan = new Db_Tables_LogsWechatScan();
		
		$row = $mod_wechat_scan->fetchRow("open_id='".$toUser."' and event_key='".$key."'");
		
		if(!$row)
		{
			$row = $mod_wechat_scan->createRow();
			$row->open_id = $toUser;
			$row->event_key = $key;
			$row->ctime = date("Y-m-d H:i:s");
			
			if($row->save())
			{
				$result = true;
			}
		}
		
		return $result;
	}
	
	function PlaceWechatUnifiedOrder($order_id)
	{
		$prepay_id = 0;
		
		$mod_params = new Db_Tables_Params();
		$WECHAT_AppID = $mod_params->GetVal("WECHAT_AppID");
		$SYS_DOMAIN = $mod_params->GetVal("SYS_DOMAIN");
        $WECHAT_MCHID = $mod_params->GetVal("WECHAT_MCHID");
		$rd = mt_rand(10000,99999);
		$nonce_str = md5($rd);
		
		$ip = $this->GetIp();
		
		$select = $this->db->select();
		$select->from("orders", array("actual_pay"));
		$select->where("order_id = ?", $order_id);
		$order_info = $this->db->fetchRow($select);
		
		if($order_info)
		{
			$select = $this->db->select();
			$select->from("orders-product", "*");
			$select->where("order_id = ?", $order_id);
			$products_info = $this->db->fetchAll($select);
			
			if(!empty($products_info))
			{
				$parr = array('goods_detail' => array());
				
				foreach($products_info as $product)
				{
					$parr['goods_detail'][] = array(
						'goods_id' => $product['product_id'],
						'goods_name' => $product['product_name'],
						'quantity' => $product['qty'],
						'price' => intval($product['unit_price']*100)
					);
				}
				
				if(!empty($parr['goods_detail']))
				{
					$detail_str = Zend_Json::encode($parr);
				}
			}
			
			$data = array(
				'appid' => $WECHAT_AppID,
				'mch_id' => $WECHAT_MCHID,
                'nonce_str' => $nonce_str,
				'body' => '全民料理-食品',
				'detail' => $detail_str,
				'out_trade_no' => $order_id,
				'total_fee' => intval($order_info['actual_pay']*100),
				'spbill_create_ip' => $ip,
				'notify_url' => $SYS_DOMAIN.'mp/pay-test',
				'trade_type' => 'JSAPI',
				'openid' => $_SESSION['identity']['wechat_openid']
			);
			
			//for test
			//$data['total_fee'] = 1;
			//for test
			$sign = $this->MakeSign($data);

			if($sign)
			{
				$contents = '<xml>
							<appid><![CDATA['.$data['appid'].']]></appid>
							<mch_id><![CDATA['.$data['mch_id'].']]></mch_id>
							<nonce_str><![CDATA['.$data['nonce_str'].']]></nonce_str>
							<body><![CDATA['.$data['body'].']]></body>
							<detail><![CDATA['.$data['detail'].']]></detail>
							<out_trade_no><![CDATA['.$data['out_trade_no'].']]></out_trade_no>
							<total_fee><![CDATA['.$data['total_fee'].']]></total_fee>
							<spbill_create_ip><![CDATA['.$data['spbill_create_ip'].']]></spbill_create_ip>
							<notify_url><![CDATA['.$data['notify_url'].']]></notify_url>
							<trade_type><![CDATA['.$data['trade_type'].']]></trade_type>
							<openid><![CDATA['.$data['openid'].']]></openid>
							<sign><![CDATA['.$sign.']]></sign>
						 </xml> ';
			}
			
			if($contents)
			{
				$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
				
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type_txt);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $contents);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				$tmpInfo = curl_exec($ch);

				if (curl_errno($ch)) {
					echo 'Errno'.curl_error($ch);
				}
				curl_close($ch);

				$result = $this->TurnMsgToObj($tmpInfo);
				if('SUCCESS' == $result->return_code)
				{
					if('SUCCESS' == $result->result_code)
					{
						$prepay_id = $result->prepay_id;
					}
				}
			}
			

			return $prepay_id;
		}
	}
	
	function PlaceWechatUnifiedOrderForRecharge($log_id, $recharge_type, $recharge_value)
	{
		$prepay_id = 0;
		
		$mod_params = new Db_Tables_Params();
		$WECHAT_AppID = $mod_params->GetVal("WECHAT_AppID");
		$SYS_DOMAIN = $mod_params->GetVal("SYS_DOMAIN");
        $WECHAT_MCHID = $mod_params->GetVal("WECHAT_MCHID");
		$rd = mt_rand(10000,99999);
		$nonce_str = md5($rd);
		
		$ip = $this->GetIp();
		
		$parr = array('goods_detail' => array());
				
		$parr['goods_detail'][] = array(
			'goods_id' => $recharge_type,
			'goods_name' => "充值".$recharge_value."元",
			'quantity' => 1,
			'price' => intval($recharge_value*100)
		);
				
		$detail_str = Zend_Json::encode($parr);
			
		$data = array(
			'appid' => $WECHAT_AppID,
			'mch_id' => $WECHAT_MCHID,
			'nonce_str' => $nonce_str,
			'body' => '全民料理-食品',
			'detail' => $detail_str,
			'out_trade_no' => "RECHARGE_".$log_id,
			'total_fee' => intval($recharge_value*100),
			'spbill_create_ip' => $ip,
			'notify_url' => $SYS_DOMAIN.'mp/pay-test',
			'trade_type' => 'JSAPI',
			'openid' => $_SESSION['identity']['wechat_openid']
		);
		
		//for test
		//$data['total_fee'] = 1;
		//for test
		
		$sign = $this->MakeSign($data);
		
		if($sign)
		{
			$contents = '<xml>
						<appid><![CDATA['.$data['appid'].']]></appid>
						<mch_id><![CDATA['.$data['mch_id'].']]></mch_id>
						<nonce_str><![CDATA['.$data['nonce_str'].']]></nonce_str>
						<body><![CDATA['.$data['body'].']]></body>
						<detail><![CDATA['.$data['detail'].']]></detail>
						<out_trade_no><![CDATA['.$data['out_trade_no'].']]></out_trade_no>
						<total_fee><![CDATA['.$data['total_fee'].']]></total_fee>
						<spbill_create_ip><![CDATA['.$data['spbill_create_ip'].']]></spbill_create_ip>
						<notify_url><![CDATA['.$data['notify_url'].']]></notify_url>
						<trade_type><![CDATA['.$data['trade_type'].']]></trade_type>
						<openid><![CDATA['.$data['openid'].']]></openid>
						<sign><![CDATA['.$sign.']]></sign>
					 </xml> ';
		}
		
		if($contents)
		{
			$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type_txt);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $contents);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$tmpInfo = curl_exec($ch);
	
			if (curl_errno($ch)) {
				echo 'Errno'.curl_error($ch);
			}
			curl_close($ch);

			$result = $this->TurnMsgToObj($tmpInfo);
			
			if('SUCCESS' == $result->return_code)
			{
				if('SUCCESS' == $result->result_code)
				{
					$prepay_id = $result->prepay_id;
				}
			}
		}
		
		return $prepay_id;
	}
	
	function PlaceWechatUnifiedOrderForVipApplication($aid, $recharge_value)
	{
		$prepay_id = 0;
		
		$mod_params = new Db_Tables_Params();
		$WECHAT_AppID = $mod_params->GetVal("WECHAT_AppID");
		$SYS_DOMAIN = $mod_params->GetVal("SYS_DOMAIN");
        $WECHAT_MCHID = $mod_params->GetVal("WECHAT_MCHID");
		$rd = mt_rand(10000,99999);
		$nonce_str = md5($rd);
		
		$ip = $this->GetIp();
		
		$parr = array('goods_detail' => array());
				
		$parr['goods_detail'][] = array(
			'goods_id' => $recharge_type,
			'goods_name' => "梦想合伙人申请-".$recharge_value."元",
			'quantity' => 1,
			'price' => intval($recharge_value*100)
		);
				
		$detail_str = Zend_Json::encode($parr);
			
		$data = array(
			'appid' => $WECHAT_AppID,
			'mch_id' => $WECHAT_MCHID,
			'nonce_str' => $nonce_str,
			'body' => '全民料理-食品',
			'detail' => $detail_str,
			'out_trade_no' => "VIP_".$aid,
			'total_fee' => intval($recharge_value*100),
			'spbill_create_ip' => $ip,
			'notify_url' => $SYS_DOMAIN.'mp/pay-test',
			'trade_type' => 'JSAPI',
			'openid' => $_SESSION['identity']['wechat_openid']
		);
		
		//for test
		//$data['total_fee'] = 1;
		//for test
		
		$sign = $this->MakeSign($data);
		
		if($sign)
		{
			$contents = '<xml>
						<appid><![CDATA['.$data['appid'].']]></appid>
						<mch_id><![CDATA['.$data['mch_id'].']]></mch_id>
						<nonce_str><![CDATA['.$data['nonce_str'].']]></nonce_str>
						<body><![CDATA['.$data['body'].']]></body>
						<detail><![CDATA['.$data['detail'].']]></detail>
						<out_trade_no><![CDATA['.$data['out_trade_no'].']]></out_trade_no>
						<total_fee><![CDATA['.$data['total_fee'].']]></total_fee>
						<spbill_create_ip><![CDATA['.$data['spbill_create_ip'].']]></spbill_create_ip>
						<notify_url><![CDATA['.$data['notify_url'].']]></notify_url>
						<trade_type><![CDATA['.$data['trade_type'].']]></trade_type>
						<openid><![CDATA['.$data['openid'].']]></openid>
						<sign><![CDATA['.$sign.']]></sign>
					 </xml> ';
		}
		
		if($contents)
		{
			$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type_txt);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $contents);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$tmpInfo = curl_exec($ch);
	
			if (curl_errno($ch)) {
				echo 'Errno'.curl_error($ch);
			}
			curl_close($ch);

			$result = $this->TurnMsgToObj($tmpInfo);
			
			if('SUCCESS' == $result->return_code)
			{
				if('SUCCESS' == $result->result_code)
				{
					$prepay_id = $result->prepay_id;
				}
			}
		}
		
		return $prepay_id;
	}
	
	function OrderRefundViaWechatPay($refund_id)
	{
		$url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
		//$merchant_id = '1410095202';
		
		$mod_params = new Db_Tables_Params();
		$appid = $mod_params->GetVal("WECHAT_AppID");
        $WECHAT_MCHID = $mod_params->GetVal("WECHAT_MCHID");
        $merchant_id = !empty($WECHAT_MCHID) ? $WECHAT_MCHID : '1410095202';
		
		$rd = mt_rand(10000,99999);
		$nonce_str = md5($rd);
		
		if($refund_id)
		{
			$mod_logs_refund = new Db_Tables_LogsRefund();
			$row = $mod_logs_refund->fetchRow("id=".intval($refund_id));
			
			if($row)
			{
				$refund_amount = intval($row->amount * 100);
				$order_id = $row->order_id;
				
				$data = array(
					'appid' => $appid,
					'mch_id' => $merchant_id,
					'nonce_str' => $nonce_str,
					'op_user_id' => $merchant_id,
					'out_refund_no' => $refund_id,
					'out_trade_no' => $order_id,
					'refund_fee' => $refund_amount,
					'total_fee' => $refund_amount
				);

				$sign = $this->MakeSign($data);

				$vars = '<xml>
<appid><![CDATA['.$appid.']]></appid>
<mch_id><![CDATA['.$merchant_id.']]></mch_id>
<nonce_str><![CDATA['.$nonce_str.']]></nonce_str>
<op_user_id><![CDATA['.$merchant_id.']]></op_user_id>
<out_refund_no><![CDATA['.$refund_id.']]></out_refund_no>
<out_trade_no><![CDATA['.$order_id.']]></out_trade_no>
<refund_fee><![CDATA['.$refund_amount.']]></refund_fee>
<total_fee><![CDATA['.$refund_amount.']]></total_fee>
<sign><![CDATA['.$sign.']]></sign>
</xml>';
			}
		}
		
		$second=30;
		$aHeader=array();
		
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_TIMEOUT,$second);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);

		curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
		curl_setopt($ch,CURLOPT_SSLCERT,'../cert/apiclient_cert.pem');
		curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
		curl_setopt($ch,CURLOPT_SSLKEY,'../cert/apiclient_key.pem');
//		curl_setopt($ch,CURLOPT_CAINFO,'/cert/rootca.pem');

		if( count($aHeader) >= 1 ){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
		}
		
		curl_setopt($ch,CURLOPT_POST, 1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
		$tmpInfo = curl_exec($ch);
		
		$success = 0;
		
		$mod_logs_refund = new Db_Tables_LogsRefund();
		$row = $mod_logs_refund->fetchRow("id=".intval($refund_id));
		
		if($tmpInfo){
			curl_close($ch);
			$result = $this->TurnMsgToObj($tmpInfo);
			
				if('SUCCESS' == $result->return_code)
				{
					if('SUCCESS' == $result->result_code)
					{
						if($row)
						{
							if(in_array($row->status, array(0,2)))
							{
								$row->status = 1;
								$row->refund_trans_id = $result->refund_id;
								$row->reason = NULL;
								$row->updated_time = date("Y-m-d H:i:s");
								$row->save();
								$success = 1;
							}
						}
					}else{
						$reason = $result->err_code_des;
					}
				}
		}else {
			$reason = "POST数据失败";
			$error = curl_errno($ch);
			echo "call faild, errorCode:$error\n"; 
			curl_close($ch);
			return false;
		}
		
		if(!$success)
		{
			if($row)
			{
				if(0 == $row->status)
				{
					if(!$reason)
					{
						$reason = "未知错误";
					}
					
					$row->status = 2;
					$row->reason = $reason;
					$row->updated_time = date("Y-m-d H:i:s");
					$row->save();
				}
			}
		}else{
			$mod_orders_joins = new Db_Joins_OrdersJoins();
			$mod_orders_joins->order_id = $row->order_id;
			$mod_orders_joins->member_id = $row->member_id;
			$mod_orders_joins->BackItemsForCanceledOrder();
		}
		
		return TRUE;
	}
	
	function WithdrawViaWechatPay($withdraw_id)
	{
		$url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
		$merchant_id = '1410095202';
		
		$mod_params = new Db_Tables_Params();
		$appid = $mod_params->GetVal("WECHAT_AppID");
		
		$rd = mt_rand(10000,99999);
		$nonce_str = md5($rd);
		
		if($withdraw_id)
		{
			$mod_logs_withdraw = new Db_Tables_LogsWithdraw();
			$row = $mod_logs_withdraw->fetchRow("id=".intval($withdraw_id));
			
			if($row)
			{
				$withdraw_value = intval($row->withdraw_value * 100);
				$member_id = $row->member_id;
				$withdraw_type = $row->withdraw_type;
				
				$mod_platform_member = new Db_Tables_PlatformMembers();
				$open_id = $mod_platform_member->GetOpenId($member_id);
				
//				$ip = $this->GetIp();
				
				$data = array(
					'mch_appid' => $appid,
					'mchid' => $merchant_id,
					'nonce_str' => $nonce_str,
					'partner_trade_no' => $withdraw_id,
					'openid' => $open_id,
					'check_name' => "NO_CHECK",
					'amount' => $withdraw_value,
					'desc' => "全民料理提现",
					'spbill_create_ip' => "118.178.120.77"
				);
				
				$sign = $this->MakeSign($data);
				
				$vars = '<xml>
<mch_appid><![CDATA['.$data['mch_appid'].']]></mch_appid>
<mchid><![CDATA['.$data['mchid'].']]></mchid>
<nonce_str><![CDATA['.$data['nonce_str'].']]></nonce_str>
<partner_trade_no><![CDATA['.$data['partner_trade_no'].']]></partner_trade_no>
<openid><![CDATA['.$data['openid'].']]></openid>
<check_name><![CDATA['.$data['check_name'].']]></check_name>
<amount><![CDATA['.$data['amount'].']]></amount>
<desc><![CDATA['.$data['desc'].']]></desc>
<spbill_create_ip><![CDATA['.$data['spbill_create_ip'].']]></spbill_create_ip>
<sign><![CDATA['.$sign.']]></sign>
</xml>';
			}
		}
		
		$second=30;
		$aHeader=array();
		
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_TIMEOUT,$second);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);

		curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
		curl_setopt($ch,CURLOPT_SSLCERT,'../cert/apiclient_cert.pem');
		curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
		curl_setopt($ch,CURLOPT_SSLKEY,'../cert/apiclient_key.pem');
//		curl_setopt($ch,CURLOPT_CAINFO,'/cert/rootca.pem');

		if( count($aHeader) >= 1 ){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
		}
		
		curl_setopt($ch,CURLOPT_POST, 1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
		$tmpInfo = curl_exec($ch);
		
		$success = 0;
		
		$mod_logs_withdraw = new Db_Tables_LogsWithdraw();
		$row = $mod_logs_withdraw->fetchRow("id=".intval($withdraw_id));
		
		if($tmpInfo){
			curl_close($ch);
			$result = $this->TurnMsgToObj($tmpInfo);
			
				if('SUCCESS' == $result->return_code)
				{
					if('SUCCESS' == $result->result_code)
					{
						if($row)
						{
							if(0 == $row->status)
							{
								$row->status = 1;
								$row->trans_id = $result->payment_no;
								$row->updated_time = date("Y-m-d H:i:s");
								$row->save();
								$success = 1;
							}
						}
					}else{
						$reason = $result->err_code_des;
					}
				}
		}else {
			$reason = "POST数据失败";
			$error = curl_errno($ch);
			echo "call faild, errorCode:$error\n"; 
			curl_close($ch);
			return false;
		}
		
		if(!$success)
		{
			if($row)
			{
				if(0 == $row->status)
				{
					if(!$reason)
					{
						$reason = "未知错误";
					}
					
					$row->status = 2;
					$row->reason = $reason;
					$row->updated_time = date("Y-m-d H:i:s");
					if($row->save())
					{
						//refund to member
						if("agent" == $withdraw_type)
						{
							$t = new Db_Tables_LogsAgent();
							$t->aid = 6;
						}elseif("vip" == $withdraw_type)
						{
							$t = new Db_Tables_LogsVip();
							$t->aid = 6;
						}elseif("delivery" == $withdraw_type)
						{
							$t = new Db_Tables_LogsDelivery();
							$t->aid = 5;
						}
						
						$t->action_value = $withdraw_value/100;
						$t->member_id = $member_id;
						$t->comments = $reason;
						$t->AddRecord();
					}
				}
			}
		}
		
		return TRUE;
	}
	
	function InBusinessHours()
	{
		$result = FALSE;
		
		$business_hours_array = array();
		
		$min = mktime(10,0,0,date("m"),date("d"),date("Y"));
		$max = mktime(23,0,0,date("m"),date("d"),date("Y"));
		
		$business_hours_array[] = array(
			'min' => $min,
			'max' => $max
		);
		
		
		
		$current_time = time();
		
		if(!empty($business_hours_array))
		{
			foreach($business_hours_array as $bh)
			{
				if($current_time >= $bh['min'] && $current_time <= $bh['max'])
				{
					$result = TRUE;
					break;
				}
			}
		}
		
		return $result;
	}
	
	function PostWebSocketMsgToClient($user_id, $content)
	{
		$url = "https://rest-hangzhou.goeasy.io/publish";
		$type = 1;
		
		$data_array = array(
			"appkey" => "BC-6a12dde99b3c4e68b717097f27ec8194",
			"content" => $content
		);
		
		if('admin' != $user_id)
		{
			$data_array['channel'] = sha1("mZ1".$user_id."als!hGj3lKe");
		}else{
			$data_array['channel'] = sha1("maozhuaAdmin");
		}
		
//		$mod_log1 = new Db_Tables_Log1();
//		$mod_log1->AddLog("PostWebSocketMsgToClient: ".Zend_Json::encode($data_array));
		
		
		$this->Broadcast($url, $data_array, $type, 0);
	}
        
	//获取微信二维码
	function GetWxcode()
	{
		$appid = "wx0a0a571c5f63f74e";
		$secret = "5029587efbe01533ea24f573bcdc2411";
		$mod_sys = new Sys_Extensions();
		$url= "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
		$data_token = array(
			"grant_type"=>"client_credential",
			"appid"=>$appid,
			"secret"=>$secret
		);
		$type = 2;
		$backdata = $mod_sys->Broadcast($url, $data_token, $type);

		$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$backdata['access_token'];
		$type = 1;
		$data_array = array(
		   "action_name"=>"QR_LIMIT_STR_SCENE",
		   "action_info"=>array(
			   "scene"=>array(
				   "scene_str"=>"123"
			   )
		   )
		);   
		$getticket = $mod_sys->Broadcast($url, $data_array, $type);   //获取二维码ticket

		$ticket = urlEncode($getticket['ticket']);
		$url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket;

		return $url;
	}  

	//发送微信模板消息
	function sendTempleteMsg($openid,$content)
	{
		$jssdk = new Db_Tables_Jssdk();
		$mod_sys = new Db_Tables_Extensions();
		$token = $jssdk->getAccessToken();
		
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
		$type = 1;
		$data_post = array(
			"touser"=>$openid,
			"template_id"=>"q5lcHHXzk4FxJO6wOub76k9kCT9jI5MnxHxJCPhsqsg",
			"data"=>array(
				"first"=>array(
					"value"=>"网媒助手温馨提示\n"
				),
				"keyword1"=>array(
				   "value"=>$content."\n",
					"color"=>"#2f91f5"
			   ),
				"keyword2"=>array(
				   "value"=>date("Y-m-d H:i:s")."\n",
					"color"=>"#2f91f5"
			   ),
				"remark"=>array(
					"value"=>"请登录网媒助手查看详情"
				)
			)
		);  
		$senddata = $mod_sys->Broadcast($url, $data_post, $type);				
		return $senddata;
	}
	
	//过滤屏蔽关键字里的字符串
	function KeywordFilter($txt, $seperator=",")
	{
		$result = "";
		
		$txt = trim($txt);
		
		$sep = NULL;
		
		$find   = ',';
		$pos = strpos($txt, $find);

		if ($pos === false) {
			
			$find   = '，';
			$pos = strpos($txt, $find);

			if ($pos === false) {

				$find   = '|';
				$pos = strpos($txt, $find);

				if ($pos === false) {

					$find   = ' ';
					$pos = strpos($txt, $find);

					if ($pos !== false) {

						$sep = $find;

					}

				} else {
					$sep = $find;
				}

			} else {
				$sep = $find;
			}
			
		} else {
			$sep = $find;
		}
		
		if($sep)
		{
			$ex = explode($sep, $txt);
			
			if(!empty($ex))
			{
				$units = array();
				
				foreach($ex as $e)
				{
					$e = trim($e);
					
					if($e)
					{
						$units[] = $e;
					}
				}
				
				if(!empty($units))
				{
					$result = implode($seperator, $units);
				}
			}
		}
		
		return $result;
	}
}